FILE_LOCATION   =	"/ifs/scratch/c2b2/ip_lab/ddd2124"

setwd(FILE_LOCATION)

BG_FILE <- read.table("background.lst.txt", header=F, stringsAsFactors=F)

poplist<-read.table("PopIndex.txt",header=F, stringsAsFactors=F)
poplist<-poplist[,1]

#enact these once you have the lengths and numbers files
Lengths<-read.table("Lengths.txt",header=F)
Numbers<-read.table("Numbers.txt",header=F)

bgl<-integer(0)
bgn<-integer(0)

for (i in seq(length(BG_FILE[,1])))
{
	if ((A<-which(poplist==BG_FILE[i,1]))<(B<-which(poplist==BG_FILE[i,2])))
	{bgl<-c(bgl,Lengths[A,B])
	 bgn<-c(bgn,Numbers[A,B])}
	else 	{bgl<-c(bcl,Lengths[B,A])
		 bgn<-c(bcn,Numbers[B,A])}
}



bglcdf<-ecdf(bgl)
bgncdf<-ecdf(bgn)

g<-length(Lengths[,1])

#####################################################
##################BG MATRICES########################

BGNMAT <- Lengths
for (i in seq(g-1))
{
	BGNMAT[i,] <- bgncdf(Numbers[i,])
	BGNMAT[i,] <- apply(rbind(BGNMAT[i,],1-BGNMAT[i,]), 2, min)
}

BGLMAT<- PCNMAT
for (i in seq(g-1))
{
	BGLMAT[i,] <- bglcdf(Lengths[i,])
	BGLMAT[i,] <- apply(rbind(BGLMAT[i,],1-BGLMAT[i,]), 2, min)
}


BGNMAT2 <- BGNMAT + t(BGNMAT)
write.table(BGNMAT2 ,"BGNMAT.txt",row.names=F,col.names=F,quote=F)
rm(BGNMAT2, BGNMAT)
gc()
BGLMAT2 <- BGLMAT + t(BGLMAT)
write.table(BGLMAT2,"BGLMAT.txt",row.names=F,col.names=F,quote=F)
rm(BGLMAT2, BGLMAT)
gc()



###############################################################################
# add matrices for avg lengths

AverageLengths <- Numbers / (Lengths + .001)

bga<-integer(0)

g<-length(AverageLengths[,1])

for (i in seq(length(BG_FILE[,1])))
{
	if ((A<-which(poplist==BG_FILE[i,1]))<(B<-which(poplist==BG_FILE[i,2])))
	{bga<-c(bga,AverageLengths[A,B])}
	else 	{bga<-c(bga,AverageLengths[B,A])}
}

bgacdf<-ecdf(bga)

BGAMAT<- AverageLengths
for (i in seq(g-1))
{
	BGAMAT[i,] <- bgacdf(AverageLengths[i,])
	BGAMAT[i,] <- apply(rbind(BGAMAT[i,],1-BGAMAT[i,]), 2, min)
}

BGAMAT<- BGAMAT+ t(BGAMAT)
write.table(BGAMAT,"BGAMAT.txt",row.names=F,col.names=F,quote=F)
rm(BGAMAT, bga, bgacdf)
gc()

################
quit()